#include<iostream>
#include<unistd.h>
#include<sys/wait.h>
#include<stdlib.h>
#include<vector>
using namespace std;

typedef void (*handler_t)();//函数指针类型
vector<handler_t> handler;//函数指针数组
void fun1()
{
  cout << "这是一个临时任务1" << endl;
}
void fun2()
{
  cout << "这是一个临时任务2" << endl;
}
void Load()//加载
{
  handler.push_back(fun1);
  handler.push_back(fun2);
}
int main()
{
  //进程非阻塞等待
  pid_t id = fork();
  if(id == 0)
  {
    //子进程
    int cnt = 8; 
    while(cnt)
    {
      cout << "我是子进程" << cnt << endl;
      sleep(1);
      cnt--;
    }
  }
  else if(id>0)
  {
    //父进程
    int quit = 0;
    while(!quit)
    {
    int status = 0;
    pid_t ret = waitpid(-1, &status, WNOHANG);
    if(ret > 0)
    {
      cout << "等待成功，子进程退出码：" << WEXITSTATUS(status);
      quit = 1;
    }
    else if(ret == 0)
    {
      cout << "等待成功，但子进程还没有终止，处理其他任务" << endl;
      if(handler.empty()) Load();
      for(auto iter : handler)
      {
        iter();
      }
    }
    else
    {
      cout << "wait失败" << endl;
      quit = 1;
    }

    sleep(1);
    }
  }
  else
  {
    cout << "fork失败" << endl;
    exit(1);
    //创建子进程失败
  }
  //cout << "进程开始执行" << endl;
  ////execl("/usr/bin/ls","ls","-a","-l",nullptr);
  //execl("/usr/bin/top", "top",nullptr);
  //exit(1);
  //cout << "进程执行结束" << endl;
  return 0;
}
